package logic

import (
	"context"
	"errors"
	"houseRpc/models"
	"time"

	"houseRpc/house"
	"houseRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateHouseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateHouseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateHouseLogic {
	return &UpdateHouseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateHouseLogic) UpdateHouse(in *house.UpdateHouseRequest) (*house.UpdateHouseResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var h models.House
	h.ID = uint(in.HouseId)
	if err = h.GetHouseById(); err != nil {
		logx.Error("房源信息获取失败")
		return nil, errors.New("房源信息获取失败")
	}

	if time.Since(h.CreatedAt) > 5*time.Minute {
		logx.Error("房源信息发布5分钟后不能修改")
		return nil, errors.New("房源信息发布5分钟后不能修改")
	}

	h.Title = in.Title
	h.Ads = in.Ads
	h.Square = in.Square
	h.Floor = in.Floor
	h.Price = float64(in.Price)

	if err = h.UpdateHouse(); err != nil {
		logx.Error("房源信息修改失败")
		return nil, errors.New("房源信息修改失败")
	}
	return &house.UpdateHouseResponse{
		HouseId: int64(h.ID),
	}, nil
}
